﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Microsoft.Forums.OfflineStore;
using System.Configuration;
using System.Windows.Threading;
using Microsoft.Forums.SyncService;
using System.Data.Linq;

namespace Microsoft.Forums.ForumsClient.Models
{
    /// <summary>
    ///  Observable collection of subscribed forums. This would be bound to the Subscribed Forums Folder
    ///  on the GUI. Add support to remove items when implementing unsubscribe
    /// </summary>
    public class SubscribedForumsCollection : DispatchingObservableCollection<ForumFolderViewModel>
    {
        /// <summary>
        ///  Constructor. Access any subscribed forums from the database and add to this collection.
        /// </summary>
        public SubscribedForumsCollection()
        {
           
        }

        /// <summary>
        ///  Updates the collection with data from the Database.
        /// </summary>
        public void Refresh()
        {
            using (var store = AppDataModel.Instance.ReadOnlyDataContext)
            {
                foreach (var f in store.Forums)
                {
                    /// Add the forum only if it's not already in our subscribed forums list.
                    if (this[f.Id] == null)
                    {
                        var forumFolderModel = new ForumFolderViewModel(f, DispatcherUI);
                        Add(forumFolderModel);
                        forumFolderModel.RefreshPostCounts();
                        AppDataModel.Instance.SynchronizationManager.AddForumToScheduler(forumFolderModel);
                    }

                }
            }
        }

        /// <summary>
        ///  Indexer that returns the forumModel object that matches the given forumId
        /// </summary>
        /// <param name="forumId">Forum Id Guid</param>
        /// <returns>ForumContainer if the Guid exists or null</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")]
        public ForumFolderViewModel this[Guid forumId]
        {
            get
            {
                if (forumId == null)
                    throw new ArgumentNullException("forumId");

                ForumFolderViewModel forumModel;

                // Only single ForumContainer should exist in this list that matches this forumId
                forumModel = this.SingleOrDefault(fc => fc.Forum.Id == forumId);

                return forumModel;
            }
        }
    }
   
}
